package com.kehutong.payfees.admin;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;

import com.kehutong.common.math.CalculatorUtils;
import com.kehutong.common.util.Token;
import org.coraframework.authz.HasPermission;
import org.coraframework.bean.valid.ValidResult;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.JSONResult;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.util.Objects;

import com.kehutong.common.errcode.Result;
import com.kehutong.payfees.entity.ChargeUserInstrument;
import com.kehutong.payfees.enums.UserInstrumentMaxRead;
import com.kehutong.payfees.service.ChargeUserInstrumentServiceImpl;

@MvcAction
@ReqMapping("/admin/charge/user/instrument")
public class ChargeUserInstrumentAction {

    @Inject
    private JdbcSession sqlSession;

    @Inject
    private ChargeUserInstrumentServiceImpl chargeUserInstrumentService;

    @HasPermission("charge:userInstrument:view")
    @ReqMapping("/list")
    public Object list(Token token, JSONObject jsonObject) throws Exception {
        if (Objects.isEmpty(jsonObject.getString("communityNo"))) {
            Page<ChargeUserInstrument> emptyData = new Page<>();
            emptyData.setList(new ArrayList<>());
            return Result.success(emptyData);
        }
        return Result.success(chargeUserInstrumentService.list(token, jsonObject));
    }

    @HasPermission("charge:userInstrument:view")
    @ReqMapping("/listAll")
    public Object listAll(JSONObject jsonObject) {
        if (Objects.isEmpty(jsonObject.getString("communityNo"))) {
            Page<ChargeUserInstrument> emptyData = new Page<>();
            emptyData.setList(new ArrayList<>());
            return Result.success(emptyData);
        }
        return Result.success(chargeUserInstrumentService.listAll(jsonObject));
    }

    @HasPermission("charge:userInstrument:view")
    @ReqMapping("/getUserInstrumentSize")
    public Object getUserInstrumentSize(JSONObject jsonObject){
        int size = sqlSession.findArray(ChargeUserInstrument.class)
                .eq(jsonObject, "communityNo", "instrumentTypeId", "appType")
                .exe().size();
        return size;
    }

    @Bean(newInstance=true, copy=true)
    @HasPermission("charge:userInstrument:edit")
    @ReqMapping("/save")
    public Object save(Token token, ChargeUserInstrument chargeUserInstrument) throws Exception {
        chargeUserInstrument.setRatio(new BigDecimal("1"));

        JSONResult check = checkEntity(chargeUserInstrument);
        if(Objects.nonNull(check)){
            return check;
        }

        ChargeUserInstrument resultUserInstrument = sqlSession.findOne(ChargeUserInstrument.class)
                .eq("communityNo", chargeUserInstrument.getCommunityNo())
                .eq("instrumentNo", chargeUserInstrument.getInstrumentNo())
                .eq("deleted", false).exe();
        if (Objects.nonNull(resultUserInstrument)) {
            return Result.error(0, "当前仪表编号不能重复");
        }
        chargeUserInstrumentService.save(token, chargeUserInstrument);
        return Result.success();
    }

    @Bean(newInstance=false, copy=true)
    @HasPermission("charge:userInstrument:edit")
    @ReqMapping("/update")
    public Object update(Token token, ChargeUserInstrument chargeUserInstrument, ValidResult result) throws Exception {

        JSONResult check = checkEntity(chargeUserInstrument);
        if(Objects.nonNull(check)){
            return check;
        }

        ChargeUserInstrument resultUserInstrument = sqlSession.findOne(ChargeUserInstrument.class)
                .eq("communityNo", chargeUserInstrument.getCommunityNo())
                .eq("instrumentNo", chargeUserInstrument.getInstrumentNo())
                .noEq("id", chargeUserInstrument.getId())
                .eq("deleted", false).exe();
        if (Objects.nonNull(resultUserInstrument)) {
            return Result.error(0, "当前仪表编号不能重复");
        }
        chargeUserInstrumentService.update(token, chargeUserInstrument);

        return Result.success();
    }

    @HasPermission("charge:userInstrument:edit")
    @ReqMapping("/delete")
    public Object delete(String id) {
        chargeUserInstrumentService.delete(id);
        return Result.success();
    }

    @HasPermission("charge:userInstrument:view")
    @ReqMapping("/get/enum")
    public Object getEnum() {
        return Result.success(Arrays.asList(UserInstrumentMaxRead.values()));
    }

    @HasPermission("charge:userInstrument:edit")
    @ReqMapping("/set/copyInstrument")
    public Object setCopyInstrument(String id, Boolean copyInstrument) {
        chargeUserInstrumentService.setCopyInstrument(id, copyInstrument);
        return Result.success();
    }

    @HasPermission("charge:userInstrument:edit")
    @ReqMapping("/set/all/copyInstrument")
    public Object setAllCopyInstrument(JSONObject jsonObject) {
        chargeUserInstrumentService.setAllCopyInstrument(jsonObject);
        return Result.success();
    }

    @HasPermission("charge:userInstrument:edit")
    @ReqMapping("/delete/ids")
    public Object deleteUserInstrumentByIds(JSONObject jsonObject) {
        JSONArray jsonArray = jsonObject.getJSONArray("ids");
        if (jsonArray.size() == 0) {
            return Result.error(0, "请选择需要删除的数据！");
        }
        chargeUserInstrumentService.deleteUserInstrumentByIds(jsonArray);
        return Result.success();
    }

    @HasPermission("charge:userInstrument:view")
    @ReqMapping("/download")
    public Object downloadUserInstrument(Token token, JSONObject jsonObject) throws Exception {
        File file = chargeUserInstrumentService.downloadUserInstrument(token, jsonObject);
        return Result.download(file);
    }

    @HasPermission("charge:userInstrument:edit")
    @ReqMapping("/readFile")
    public Object readUserInstrumentFile(Token token, JSONObject jsonObject) throws Exception {
        return chargeUserInstrumentService.readUserInstrumentFile(token, jsonObject);
    }

    @HasPermission("charge:userInstrument:view")
    @ReqMapping("/export")
    public Object  exportUserInstrumentFile(Token token, JSONObject jsonObject) throws Exception {
        File file = chargeUserInstrumentService.exportUserInstrumentFile(token, jsonObject);
        return Result.download(file);
    }

    private JSONResult checkEntity (ChargeUserInstrument chargeUserInstrument) {
        if (Objects.isEmpty(chargeUserInstrument.getHouseId())){
            return Result.error(0, "请选择关联房屋");
        }

        if (Objects.isEmpty(chargeUserInstrument.getInstrumentNo())){
            return Result.error(0, "请录入仪表编号");
        }

        if (Objects.isNull(chargeUserInstrument.getMaxRead())){
            return Result.error(0, "请选择最大读数");
        }

        if (Objects.isNull(chargeUserInstrument.getLateRead())){
            return Result.error(0, "请录入当前读数");
        }

        BigDecimal lateRead = chargeUserInstrument.getLateRead();
        if (CalculatorUtils.getDecimalPlace(lateRead) > 1) {
            return Result.error(0, "当前仪表读数小数位最多支持1位");
        }
        BigDecimal maxRead = new BigDecimal(chargeUserInstrument.getMaxRead().getDesc());
        if (maxRead.compareTo(lateRead) == -1) {
            return Result.error(0, "当前仪表读数已经超过最大读数");
        }

        if (Objects.isEmpty(chargeUserInstrument.getReadDate())){
            return Result.error(0, "请选择读数日期");
        }

        return null;
    }
}
